package com.example.crm.service;

import com.example.crm.entity.Users;
import com.example.crm.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder; // 1. 导入PasswordEncoder
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UsersService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder; // 2. 注入加密器


    public Users register(Users users) {//注册
        // 检查用户名是否已经存在
        if (userRepository.findByUsername(users.getUsername()).isPresent()) {
            throw new IllegalStateException("错误：用户名 '" + users.getUsername() + "' 已被注册！");
        }

        String encodedPassword = passwordEncoder.encode(users.getPassword());// 对密码进行加密
        users.setPassword(encodedPassword);


        return userRepository.save(users);//保存到数据库
    }


    public Optional<Users> login(String username, String rawPassword) {
        // 根据用户名查找用户
        Optional<Users> optionalUser = userRepository.findByUsername(username);


        if (optionalUser.isPresent()) {
            Users users = optionalUser.get();
            // 依旧加密
            if (passwordEncoder.matches(rawPassword, users.getPassword())) {
                return optionalUser;
            }
        }

        return Optional.empty(); // 用户不存在或密码错误
    }
}